<template>
  <div class="yu-tree">
    <div
      class="yu-tree-item"
      :class="!openID.includes(v.id) ? 'open' : null"
      v-for="(v, i) in list"
      :key="i"
    >
      <div class="yu-tree-item__header" @click.stop="onClick(v)">
        <span>{{ v.text ? v.text : v.name }}</span>
        <van-icon
          name="arrow-down"
          v-if="Array.isArray(v.children) && v.children.length"
          @click.stop="toggleOpen(v)"
        />
      </div>
      <div
        class="yu-tree-item__content"
        v-if="Array.isArray(v.children) && v.children.length"
      >
        <tree :list="v.children" :level="level + 1" @change="onClick" />
      </div>
    </div>
  </div>
</template>

<script>
import { Icon } from "vant";

export default {
  name: "Tree",
  components: {
    [Icon.name]: Icon,
  },
  props: {
    list: Array,
    level: {
      type: String,
      default: "0",
    },
  },
  data() {
    let activeNames = this.list.map((v, i) => (this.level || "0") + i);
    return {
      activeNames,
      openID: [],
    };
  },
  methods: {
    onClick(val) {
      this.$emit("change", val);
    },
    toggleOpen(v) {
      if (this.openID.includes(v.id)) {
        const index = this.openID.indexOf(v.id);
        this.openID.splice(index, 1);
      } else {
        this.openID.push(v.id);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.yu-tree {
  font-size: 14px;
  color: #323233;

  .yu-tree-item__header {
    padding: 10px 0;
    margin: 0 10px;
    box-sizing: border-box;
    border-bottom: 1px solid #ebedf0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;

    &:active {
      background-color: #f2f3f5;
    }

    .van-icon {
      transition: transform 0.3s;
    }
  }

  .yu-tree-item__content {
    margin-left: 14px;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.3s ease-in-out;
    will-change: max-height;
  }

  .yu-tree-item.open {
    > .yu-tree-item__header {
      > .van-icon {
        transform: rotate(-180deg);
      }
    }

    > .yu-tree-item__content {
      max-height: 1000px;
    }
  }
}
</style>